import type {
  clearStorageFunction,
  getStorageFunction,
  getTokenFunction,
  removeStorageFunction,
  setStorageFunction,
  setTokenFunction
} from '@/types/storage'

/**
 * 获取缓存
 * @param key 存储key
 * @returns 数据
 */
export const getStorage: getStorageFunction = <T extends any>(key: string): T =>
  JSON.parse(localStorage.getItem(key) as any) as T

/**
 * 设置缓存
 * @param key 存储key
 * @param data 数据
 */
export const setStorage: setStorageFunction = <T extends any>(key: string, data: T): void =>
  localStorage.setItem(key, JSON.stringify(data))

/**
 * 移除指定 key 的缓存
 * @param key 关键key
 */
export const removeStorage: removeStorageFunction = (key: string): void => localStorage.removeItem(key)

/**
 * 清空缓存
 */
export const clearStorage: clearStorageFunction = (): void => localStorage.clear()

/**
 * 设置token
 */
export const setToken: setTokenFunction = (data: string): void => localStorage.setItem('token', data)

/**
 * 获取token
 */
export const getToken: getTokenFunction = (): string => localStorage.getItem('tokem') as string
